package com.edu.exam.entity.examination.template;

import com.edu.exam.enums.common.WorkflowStatus;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 试卷模板实体类
 * 所属模块：F-07 基础数据管理模块
 * 对应数据库表：exam_templates
 *
 * 管理试卷的格式和结构模板，包含模板的内容、样式、适用考试类型列表等。
 * 支持模板的生成、验证和样式更新。
 *
 * @author System
 * @version 1.0.0
 */
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "exam_templates")
@Comment("试卷模板表")
public class ExamTemplate {

    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    /**
     * 模板代码，唯一标识符
     */
    @NotBlank(message = "模板代码不能为空")
    @Size(max = 50, message = "模板代码长度不能超过50个字符")
    @Column(name = "template_code", nullable = false, unique = true, length = 50)
    private String templateCode;

    /**
     * 模板名称
     */
    @NotBlank(message = "模板名称不能为空")
    @Size(max = 100, message = "模板名称长度不能超过100个字符")
    @Column(name = "template_name", nullable = false, length = 100)
    private String templateName;

    /**
     * 模板类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "template_type", nullable = false, length = 20)
    private WorkflowStatus templateType;

    /**
     * 模板内容
     */
    @Lob
    @Column(name = "template_content", columnDefinition = "JSON")
    private String templateContent;

    /**
     * 样式定义
     */
    @Lob
    @Column(name = "style_definition", columnDefinition = "JSON")
    private String styleDefinition;

    /**
     * 适用考试类型
     */
    @Size(max = 200, message = "适用考试类型长度不能超过200个字符")
    @Column(name = "applicable_exam_types", length = 200)
    private String applicableExamTypes;

    /**
     * 总分
     */
    @Column(name = "total_score")
    @Builder.Default
    private Integer totalScore = 100;

    /**
     * 题目数量
     */
    @Column(name = "question_count")
    private Integer questionCount;

    /**
     * 预估考试时间（分钟）
     */
    @Column(name = "estimated_time")
    private Integer estimatedTime;

    /**
     * 是否默认模板
     */
    @Column(name = "is_default")
    @Builder.Default
    private Boolean isDefault = false;

    /**
     * 是否系统预定义
     */
    @Column(name = "is_system")
    @Builder.Default
    private Boolean isSystem = false;

    /**
     * 是否激活
     */
    @Column(name = "is_active")
    @Builder.Default
    private Boolean isActive = true;

    /**
     * 使用次数
     */
    @Column(name = "usage_count")
    @Builder.Default
    private Long usageCount = 0L;

    /**
     * 状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "status", nullable = false, length = 20)
    @Builder.Default
    private WorkflowStatus status = WorkflowStatus.DRAFT;

    /**
     * 审核状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "approval_status", length = 20)
    private String approvalStatus;

    /**
     * 审核人
     */
    @Size(max = 50, message = "审核人长度不能超过50个字符")
    @Column(name = "approved_by", length = 50)
    private String approvedBy;

    /**
     * 审核时间
     */
    @Column(name = "approval_date")
    private LocalDateTime approvalDate;

    /**
     * 审核意见
     */
    @Size(max = 500, message = "审核意见长度不能超过500个字符")
    @Column(name = "approval_comments", length = 500)
    private String approvalComments;

    /**
     * 描述信息
     */
    @Size(max = 1000, message = "描述信息长度不能超过1000个字符")
    @Column(name = "description", length = 1000)
    private String description;

    /**
     * 创建时间
     */
    @Column(name = "created_time", nullable = false, updatable = false)
    private LocalDateTime createdTime;

    /**
     * 更新时间
     */
    @Column(name = "updated_time", nullable = false)
    private LocalDateTime updatedTime;

    /**
     * 创建人
     */
    @Size(max = 50, message = "创建人长度不能超过50个字符")
    @Column(name = "created_by", nullable = false, length = 50)
    private String createdBy;

    /**
     * 更新人
     */
    @Size(max = 50, message = "更新人长度不能超过50个字符")
    @Column(name = "updated_by", length = 50)
    private String updatedBy;

    @PrePersist
    protected void onCreate() {
        LocalDateTime now = LocalDateTime.now();
        this.createdTime = now;
        this.updatedTime = now;
    }

    @PreUpdate
    protected void onUpdate() {
        this.updatedTime = LocalDateTime.now();
    }

    /**
     * 验证模板内容
     */
    public boolean validateTemplateContent() {
        return templateContent != null && !templateContent.trim().isEmpty();
    }

    /**
     * 生成模板实例
     */
    public String generateTemplateInstance() {
        if (templateContent == null) {
            return "";
        }
        // 简单的模板处理，实际应用中可能需要更复杂的模板引擎
        return templateContent.replace("${templateName}", templateName)
                .replace("${totalScore}", String.valueOf(totalScore));
    }

    /**
     * 更新模板样式
     */
    public boolean updateTemplateStyle(String newStyle) {
        if (newStyle == null || newStyle.trim().isEmpty()) {
            return false;
        }
        this.styleDefinition = newStyle;
        return true;
    }

    /**
     * 获取适用考试类型列表
     */
    public List<String> getApplicableExamTypes() {
        if (applicableExamTypes == null || applicableExamTypes.trim().isEmpty()) {
            return List.of();
        }
        return Arrays.stream(applicableExamTypes.split("[,;，；]"))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }
}